package com.ovopark.organize.server.oss;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.*;
import java.util.Random;

/**
 * oss帮助类
 * @author CYL
 *
 */
@Component
@Slf4j
public class OssHelper {

//	private static Logger logger = LoggerFactory.getLogger(OssHelper.class);
	/**
	 * 走文件服务器
	 */

	private static String fileStorageType;

	// 上传类型枚举，默认是阿里云oss
	private static StorageType storageType = StorageType.aliyun;

	@Value("${fileStorageType}")
	public void setFileStorageType(String fileStorageType) {
		this.fileStorageType = fileStorageType;
		// 加入配置了，按照配置的类型
		if (!StringUtils.isEmpty(fileStorageType)) {
			storageType = StorageType.valueOf(fileStorageType);
		}
	}

	/**
	 * 图片上传
	 * @param file
	 * @return
	 */
	public static String uploadFile(File file, StorageModule module){
		String url = null;
		OssResult ossResult = StorageUploader.upload(file, storageType, module);
		if (ossResult != null) {
			url = ossResult.getAccessUrl();
		}
		return url;
	}
	
	public static String uploadFile1(File file, String fileName, StorageModule module){
		String url = null;
		OssResult ossResult = StorageUploader.upload(file, storageType, module);
		if (ossResult != null) {
			url = ossResult.getAccessUrl();
		}
		return url;
	}
	
	
	public static String uploadFileExt(File file,String ext, StorageModule module){
		String url = null;
		OssResult ossResult = StorageUploader.upload(file, storageType, module);
		if (ossResult != null) {
			url = ossResult.getAccessUrl();
		}
		return url;
	}

	public static String uploadFileWithPre(File file,String ext,String orginFileName, StorageModule module){
		String url = null;
		OssResult ossResult = StorageUploader.upload(file, storageType, module);
		if (ossResult != null) {
			url = ossResult.getAccessUrl();
		}
		return url;
	}

	public static String uploadFileInputStreamExtWithName(InputStream fileInputStream,String ext, StorageModule module){
		//取当前时间的长整形值包含毫秒
		long millis = System.currentTimeMillis();
		//加上三位随机数
		Random random = new Random();
		int end3 = random.nextInt(999);
		//如果不足三位前面补0
		String str = millis + String.format("%03d", end3);
		try {
			File tempFile = File.createTempFile(str, ext);
			toFile(fileInputStream, tempFile);
			log.info("temp file:" + tempFile.getName());
			String url = null;
			OssResult ossResult = StorageUploader.upload(tempFile, storageType, module);
			if (ossResult != null) {
				url = ossResult.getAccessUrl();
			}
			log.info("final url:" + url);
			return url;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "error";
	}
	public static String uploadFileWithName(File file,String fileName, StorageModule module){
		String url = null;
		OssResult ossResult = StorageUploader.upload(file, storageType, module);
		if (ossResult != null) {
			url = ossResult.getAccessUrl();
		}
		return url;
	}

	public static byte[] is2ByeteArray(InputStream is) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buff = new byte[8192];
		int rc = 0;
		while((rc=is.read(buff, 0, 8192))>0) {
			baos.write(buff, 0, rc);
		}

		return baos.toByteArray();
	}

	private static void toFile(InputStream ins,File file) throws IOException {
		OutputStream os = new FileOutputStream(file);
		int bytesRead = 0;
		byte[] buffer = new byte[8192];
		while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
			os.write(buffer, 0, bytesRead);
		}
	}

	/**
	 * 使用httpclient下载图片，返回图片流,参数需要使用全路径
	 * @param fullUrl
	 * @return
	 */
	public static InputStream download(String fullUrl){
		InputStream input = null;
		if (!StringUtils.isEmpty(fullUrl)) {
			try {
				// 假如是https，转换成http再下载
				if (fullUrl.startsWith("https")) {
					fullUrl = fullUrl.replaceFirst("https", "http");
				}
				input = StorageUploader.download(fullUrl);
			} catch (Exception e) {
				log.error("download", e);
			}
		}
		return input;
	}

	/**
	 * 删除oss文件需要相对路径
	 */
	public static void deleteFile(String filePath,StorageModule storageModule){
		if (!StringUtils.isEmpty(filePath)) {
			// 假如是全路径，删除前面域名部分
			if (filePath.startsWith("http")) {
				// https://xxxxx.xx/check/2021/08/23/fffff.jpg
				int index = org.apache.commons.lang3.StringUtils.ordinalIndexOf(filePath, "/", 3);
				//filePath =  2021/08/23/fffff.jpg
				filePath = filePath.substring(index+1);
			}
			StorageUploader.deleteFile(storageType, filePath,storageModule);
		}
	}

	//判断OSS服务文件上传时文件的contentType 
	private static String contentType(String fileType) {
		fileType = fileType.toLowerCase();
		String contentType = "";  
        switch (fileType) {  
        case "bmp": contentType = "image/bmp";  
                    break;  
        case "gif": contentType = "image/gif";  
                    break;  
        case "png":   
        case "jpeg":      
        case "jpg": contentType = "image/jpeg";  
                    break;  
        case "html":contentType = "text/html";  
                    break;  
        case "txt": contentType = "text/plain";  
                    break;  
        case "vsd": contentType = "application/vnd.visio";  
                    break;  
        case "ppt":   
        case "pptx":contentType = "application/vnd.ms-powerpoint";  
                    break;  
        case "doc":   
        case "docx":contentType = "application/msword";  
                    break;  
        case "xml":contentType = "text/xml";  
                    break;  
        case "mp4":contentType = "video/mp4";  
                    break;  
        default: contentType = "application/octet-stream";  
                    break;  
        }
        return contentType;  
	}


	/**
	 * 图片上传
	 * @param file
	 * @return
	 */
	public static String uploadFileNew(File file,String path,String customFileName){
		String url = null;
		OssResult ossResult = StorageUploader.uploadNewFile(file,path,customFileName);
		if (ossResult != null) {
			url = ossResult.getAccessUrl();
		}
		return url;
	}

}
